package com.mall.commons.tool.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author lichao
 * @createdate 2021-01-25 14:32
 */
public class String2ListTyperHandler extends BaseTypeHandler<List> {


    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i,list.toString());
    }

    private List<String> string2List(String str){
        if(str == null || str.length() == 0){
            return null;
        }
        String[] strings = str.split(",");
        List<String> list = new LinkedList<>();
        for (int i = 0; i < strings.length; i++) {
            list.add(strings[i]);
        }
        return list;
    }

    @Override
    public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return string2List(resultSet.getString(s));
    }

    @Override
    public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return string2List(resultSet.getString(i));
    }

    @Override
    public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return string2List(callableStatement.getString(i));
    }
}
